<template>
    <div class="content-box">
      <div ref="searchBox" class="search-box flex" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="100px"
        >
        <el-form-item label="关联公司" prop="companyIds" >
            <el-select
             v-model="queryParams.companyIds"
             multiple
             collapse-tags
             clearable
             filterable
             placeholder="请选择"
             style="width: 240px; margin-right: 20px"
            >
              <el-option
               v-for="(item, index) in companyIdOption"
               :key="index"
               :label="item.companyName"
               :value="item.id"
               ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="管理人" prop="manageUserIds">
            <el-select
              v-model="queryParams.manageUserIds"
              multiple
              collapse-tags
              clearable
              filterable
              placeholder="请选择管理人"
              style="width: 240px; margin-right: 20px"
            >
              <el-option
                v-for="(item, index) in manageOptionList"
                :key="index"
                :label="item.userName"
                :value="item.userId"
              ></el-option>
            </el-select>
        </el-form-item>

        <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              plain
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
  
      <div class="table-box">
        <el-row :gutter="10" class="mb8">
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="handleQuery"
            :columns="columns"
          ></right-toolbar>
        </el-row>
        <el-table
          v-sticky-header
          ref="table"
          v-loading="loading"
          :data="dataList"
        >
          <template v-for="(item,index) in columns.slice(0, columns.length - 1)">
            <el-table-column
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :width="getColumnWidth(index)"
              align="center"
              :fixed="item.fixed"
              :sortable="item.sortable ? item.sortable : false"
              :show-overflow-tooltip="item.showTooltip"
              v-if="item.visible"
            >
            </el-table-column>
          </template>
          <el-table-column
             fixed="right"
             :prop="columns[columns.length - 1].prop"
             :label="columns[columns.length - 1].label"
             align="center"
             :width="getColumnWidth(columns.length - 1)"
              v-if="columns[columns.length - 1].visible"
           >
             <template slot-scope="scope">
              <el-button
                type="text"
                @click="handelDialog(scope.row)"
                >余额调整</el-button
               >
             </template>
          </el-table-column>
        </el-table>
        <!-- 使用分页插件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page-sizes="[10, 50, 100, 200, 500]"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
      <!-- 余额调整 对话框 -->
      <el-dialog
        title="余额调整"
        width="800px"
        :visible.sync="dialogShow"
        :before-close="handleClose"
        v-loading="apiLoading"
      >
      <el-form :model="form" :rules="rules" label-width="140px" ref="formRef" >
        <el-form-item label="公司账户id" prop="id" >
           <el-input
             v-model="form.id"
             placeholder="请输入"
             clearable
             disabled
             style="width: 100%"
           />
        </el-form-item>
        <el-form-item label="资金类型" prop="moneyType">
           <el-select
             v-model="form.moneyType"
             clearable
             filterable
             placeholder="请选择"
             style="width: 100%"
           >
             <el-option
               v-for="(item, index) in moneyTypeOption"
               :key="index"
               :label="item.label"
               :value="item.value"
             ></el-option>
           </el-select>
        </el-form-item>
        <el-form-item
         v-if="[1,3].includes(form.moneyType)"
         label="凭证地址" prop="">
           <el-input
           v-model="form.url"
           placeholder="请输入"
           clearable
           style="width: 100%"
           />
        </el-form-item>
        <el-form-item label="变更类型" prop="changeType">
           <el-select
             v-model="form.changeType"
             clearable
             filterable
             placeholder="请选择"
             style="width: 100%"
           >
             <el-option
               v-for="(item, index) in changeTypeOption"
               :key="index"
               :label="item.label"
               :value="item.value"
             ></el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="调整日期" prop="changeTime">
          <el-date-picker
           v-model="form.changeTime"
           type="date"
           style="width: 100%"
           value-format="yyyy-MM-dd"
           placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="调整金额" prop="money">
          <el-input-number 
              v-model="form.money" 
              controls-position="right" 
              placeholder="请输入"
              :min="0" 
              :precision="2"
              style="width: 100%;"
          >
          </el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            placeholder="请输入"
            type="textarea"
            clearable
            maxlength="100"
            show-word-limit
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="handleSubmit('formRef')"
          >确 定</el-button
        >
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
    </div>
  </template>
  
  <script>
  import tableStickyMixins from "@/mixins/tableStickyMixins";
  import { mapGetters } from "vuex";
  import { getUpCompanyList } from '@/api/business/upCompanyManagement'
  import { querySysUserManageList } from "@/api/system/userManage";

  import {
    listUpAccount,
    addMoney
  } from "@/api/userPermissions/upAccount";
  import moment from "moment";
  
  export default {
    // 定义名字用于标识该组件是否被keep-alive缓存
    name: "UpAccount",
    data() {
      return {
        // 数据列表
        dataList: [],
        // 关联公司筛选项
        companyIdOption: [],
        // 管理人筛选项
        manageOptionList: [],
        // 变更类型筛选项
        changeTypeOption: [
          { label: "增加", value: 1 },
          { label: "减少", value: 2 },
        ],
         // 资金类型筛选项
         moneyTypeOption: [
          { label: "充值", value: 1 },
          { label: "核销", value: 2 },
          { label: "退款", value: 3 },
          { label: "对冲", value: 4 },
          { label: "预警", value: 6 },
          { label: "补偿", value: 8 },
        ],
        // 总条数
        total: 0,
        // 查询参数
        queryParams: {
          pageIndex: 1,
          pageSize: 10,
        },
        loading: false,
        // 表格列信息
        columns: [
        {label: `上游公司名称`,prop: "companyName",visible: true,pcWidth: 160,mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `上游公司简称`,prop: "simpleName",visible: true,pcWidth: 160,mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `充值金额`,prop: "inMoney",visible: true,pcWidth: 130,mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `消耗金额`,prop: "useMoney",visible: true,pcWidth: 130,mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `账户余额`,prop: "surplusMoney",visible: true,pcWidth: 140,mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `核销金额`,prop: "obviateMoney",visible: true,pcWidth: 130,mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `对冲金额`,prop: "offsetMoney",visible: true,pcWidth: 130,mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `退款金额`,prop: "refundMoney",visible: true,pcWidth: 130,mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `预警金额`,prop: "warnMoney",visible: true,pcWidth: 130,mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `产品管理员`,prop: "manageUserName",visible: true,pcWidth: 130,mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `创建时间`,prop: "createTime",visible: true,pcWidth: 155,mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `操作`,prop: "operation",visible: true,pcWidth: 100,mobileWidth: 80,fixed: "right",showTooltip: true},
        ],
        // 显示搜索栏
        showSearch: true,
        // 弹框显示状态
        dialogShow: false,
        // 弹框的表单信息
        form: {},
        // 弹框表单校验规则
        rules: {},
        // 余额调整接口加载状态
        apiLoading:false,
      }
    },
    mixins: [tableStickyMixins],
    watch: {
      columns: {
        handler() {
          this.updateTableHeight();
        },
        deep: true,
      },
    },
    created() {
      this.init();
      this.getManageList();
      this.getcompanyIdList();
    },
    computed: {
      ...mapGetters(["sidebar", "device"]),
      // 计算当前列元素在所处环境的宽度
      getColumnWidth() {
        return (index) => {
          return this.isMobile
            ? this.columns[index].mobileWidth
            : this?.sidebar?.opened
            ? this.columns[index].pcWidth - this.slightWidth
            : this.columns[index].pcWidth + 17;
        };
      },
      
    },
    methods: {
      // 获取管理人列表
      getManageList() {
        querySysUserManageList().then((res) => {
           this.manageOptionList = res?.data;
        });
      },
      // 获取关联公司列表
      getcompanyIdList() {
        getUpCompanyList().then((res) => {
           this.companyIdOption = res.data;
        });
      },
      // 处理对话框
      handelDialog(row) {
        this.$set(this.form,'id',row?.id)
        this.dialogShow = true;
      },
      /*关闭弹窗*/
      handleClose(){
        this.$refs['formRef'].resetFields();
        this.form = this.$options.data().form;
        this.dialogShow = false;
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.$set(this.queryParams, "pageIndex", 1);
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        // 完全重置到初始状态
        this.$set(this, "queryParams", {
          pageIndex: 1,
          pageSize: 10,
        });
        this.init();
      },
      init() {
        this.getList();
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        listUpAccount(this.queryParams).then((response) => {
          // 解决id为number类型精度丢失问题
          this.dataList = response?.data?.list.map((row) => {
            return {
              ...row,
              id: row.id.toString(),
            };
          });
          this.total = response?.data?.total;
          this.loading = false;
        }).catch((err) => {
          setTimeout(() => {// 延迟2s后自动取消加载状态
            this.loading = false;
          }, 2000);
        })
      },
      // 修改表格高度触发回调
      updateTableHeight() {
        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });
      },
      /*提交操作*/
      handleSubmit(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let params={};
            params = JSON.parse(JSON.stringify(this.form))
            // 调整金额转化为两位小数
            if(params.money != null){
              params.money = params.money.toFixed(2)
            }
            console.log(params);
            // 开启接口加载状态
            this.apiLoading = true;
            let timer 
            timer && clearTimeout(timer)
            addMoney(params).then(res=>{
              if(res.code === 200){
                  this.apiLoading = false;
                  this.$message.success("操作成功");
                  this.handleClose();
                  this.getList();
              }
            }).catch(erro=>{
               timer = setTimeout(()=>{
                this.apiLoading = false;
                this.handleClose();
                this.getList();
              },2000)
            })

          }
        })
      }
      
    },
  };
  </script>
  
  <style scoped lang="scss">
  .title {
    font-size: 20px;
    color: #333333;
    font-weight: 500;
  }
  .search-box {
    margin: 0 0 20px;
    padding: 20px 20px 0;
    background: #fff;
    align-items: flex-start;
    border-radius: 6px;
  }
  .search-area {
    position: absolute;
    right: 20px;
  }
  .el-form-item__content {
    flex: 1;
    line-height: 40px;
    position: relative;
    font-size: 14px;
    min-width: 0;
  }
  ::v-deep .el-dialog__body {
    border-top: 1px solid #dfe6ec;
    border-bottom: 1px solid #dfe6ec;
  }
  .el-table {
    // 滚动条加粗
    --scrollbar-height: 9px;
  }
  </style>
  